package com.yige.service.mongoService

import com.mongodb.BasicDBObject
import com.mongodb.DBCollection
import com.mongodb.DBObject
import com.yige.common.SystemConstant
import com.yige.service.RoleService
import org.springframework.beans.factory.annotation.Autowired
import org.springframework.stereotype.Service

/**
 * Created by sunhao on 2015/9/17 0017.
 */

@Service
class MongoRoleService extends BasicMongoServiceImp implements RoleService {

    DBCollection getCollection(){
        return mongoTemplate.getCollection(SystemConstant.MONGODB_COL_ROLE)
    }

    @Override
    List<DBObject> findAllResourceForRole(Object roleId) {
        DBObject role = findOneById(roleId)
        List<DBObject> resourceList = role.resource
        return resourceList
    }

    @Override
    boolean bindResourceForRole(Object roleId, Object resourceId) {
        List<DBObject> resourceList = findAllResourceForRole(roleId) as ArrayList<DBObject>
        resourceList.add(resourceId)
        updateResourceForRole(roleId,resourceList)
        return true
    }

    @Override
    boolean removeResourceForRole(Object roleId, Object resourceId) {
        List<DBObject> resourceList = findAllResourceForRole(roleId) as ArrayList<DBObject>
        resourceList.remove(resourceId)
        updateResourceForRole(roleId, resourceList)
        return true
    }

    @Override
    boolean updateResourceForRole(Object roleId, List<DBObject> resources) {
        getCollection().update(
                [_id: roleId]as BasicDBObject,
                [$set:[resource:resources]as BasicDBObject]as BasicDBObject
        )
        return true
    }
}
